#include "lru.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

/**
 * 函数：模拟LRU页面置换算法。
 *
 * @param queue_frames 一个字符串，表示页面访问序列。
 *                     字符串中的每个字符是一个数字，表示一个页面号。
 * @param num_frames   页框的数量，表示物理内存中可用的页框数。
 */
 
 void printPageQuery(int *pages, int num, int page_num) {
	printf("Access:%d,Frames: [" ,page_num);	
	for (int i = 0; i < num; i++) {
		printf("%d", pages[i]);
		if (i != num - 1) printf(",");	
	}
	printf("]\n");
}
 
void
lru_page_replacement (char *queue_frames, int num)
{
	int pages[num], times[num];
	for (int i = 0; i < num; i++) pages[i] = times[i] = -1;

	int time = 1, replace_index = 0, min_time = 0x3f3f3f3f;

	for (size_t i = 0; i < strlen(queue_frames); i++) {
		int is_present = 0;
		min_time = 0x3f3f3f3f;
		if (queue_frames[i] == ',') continue;
		int page_num = queue_frames[i] - '0';
		for (int j = 0; j < num; j++) {
			if (pages[j] == page_num) {
				is_present = 1;
				times[j] = time;
			}
			if (times[j] < min_time) {
				replace_index = j;
				min_time = times[j];
			}

		}
		if (!is_present) {
			pages[replace_index] = page_num;
			times[replace_index] = time;
		}
		time++;
		printPageQuery(pages, num, page_num);
	}

}
